package by.alex.dzeshko.lastfmsimple.app.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import by.alex.dzeshko.lastfmsimple.R;
import by.alex.dzeshko.lastfmsimple.adapter.AlbumsCursorAdapter;
import by.alex.dzeshko.lastfmsimple.api.LastFmApi;
import by.alex.dzeshko.lastfmsimple.app.activity.DetailActivity;
import by.alex.dzeshko.lastfmsimple.app.fragment.AlbumsListFragment.Callbacks;
import by.alex.dzeshko.lastfmsimple.appstate.AppState.ScreenState;
import by.alex.dzeshko.lastfmsimple.content.Contract;
import by.alex.dzeshko.lastfmsimple.service.InfoService;
import by.alex.dzeshko.lastfmsimple.service.common.CommonService;

import com.actionbarsherlock.app.SherlockFragment;

public class ArtistDetailFragment extends SherlockFragment implements
		LoaderCallbacks<Cursor>, OnItemClickListener {

	private static String[] PROJECTION = new String[] {
			Contract.AlbumsColumns.ARTIST, Contract.AlbumsColumns.NAME,
			Contract.AlbumsColumns.MARKER, Contract.AlbumsColumns.MBID,
			Contract.AlbumsColumns.IMAGE_MEDIUM };

	private ListView mAlbumsListView;

	private ImageView mCoverImageView;

	private ProgressBar mProgressBar;

	private AlbumsCursorAdapter mCursorAdapter;

	private String mCoverUrl, mTableMarker;

	private BroadcastReceiver mBroadcastReceiver;

	private Callbacks mCallbacks;

	public static final String ALBUM_MBID = "ALBUM_MBID";

	public static final String ALBUM_COVER = "COVER";

	public ArtistDetailFragment() {
	}

	@Override
	public void onAttach(Activity activity) {
		if (!(activity instanceof Callbacks)) {
			throw new IllegalStateException(
					"Activity must implement fragment's callbacks.");
		}
		mCallbacks = (Callbacks) activity;
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
		Bundle args = getArguments();
		mCoverUrl = args.getString(DetailActivity.COVER);
		mTableMarker = args.getString(DetailActivity.MARKER);
		Intent info = new Intent(getSherlockActivity(), InfoService.class);
		if (args.containsKey(DetailActivity.MBID)) {
			String url = LastFmApi.getArtistAlbums(args
					.getString(DetailActivity.MBID));
			args.putString(InfoService.URL, url);
			info.putExtra(DetailActivity.ARGUMENTS, args);
			getSherlockActivity().startService(info);
		} else if (args.containsKey(DetailActivity.ARTIST)) {
			String url = LastFmApi.getArtistAlbumsByName(args
					.getString(DetailActivity.ARTIST));
			args.putString(InfoService.URL, url);
			info.putExtra(DetailActivity.ARGUMENTS, args);
			getSherlockActivity().startService(info);
		}
		mCursorAdapter = new AlbumsCursorAdapter(getSherlockActivity(), null);
		mBroadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(InfoService.ACTION_ON_ERROR)) {
					mProgressBar.setVisibility(View.GONE);
					Toast.makeText(
							getSherlockActivity(),
							intent.getStringExtra(CommonService.EXTRA_KEY_MESSAGE),
							Toast.LENGTH_SHORT).show();
				} else if (action.equals(InfoService.ACTION_ON_SUCCESS)) {
					mProgressBar.setVisibility(View.GONE);
				}
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(InfoService.ACTION_ON_ERROR);
		filter.addAction(InfoService.ACTION_ON_SUCCESS);
		getSherlockActivity().registerReceiver(mBroadcastReceiver, filter);
		getSherlockActivity().getSupportLoaderManager().initLoader(4, null,
				this);
	}

	@Override
	public void onDestroy() {
		getSherlockActivity().unregisterReceiver(mBroadcastReceiver);
		super.onDestroy();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_albums_detail, null);
		mAlbumsListView = (ListView) rootView
				.findViewById(R.id.listview_fragment_albumdetails);
		mCoverImageView = (ImageView) rootView
				.findViewById(R.id.view_fragment_albumsdetails_background);
		mProgressBar = (ProgressBar) rootView
				.findViewById(R.id.progressbar_fragment_albumdetails);
		// ImageLoader.getInstance().bind(mCoverImageView, mCoverUrl); check
		// cover url
		mAlbumsListView.setAdapter(mCursorAdapter);
		mAlbumsListView.setOnItemClickListener(this);
		return rootView;
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle bundle) {
		return new CursorLoader(getSherlockActivity(),
				Contract.AlbumsColumns.CONTENT_URI, PROJECTION,
				Contract.AlbumsColumns.MARKER + " = ?",
				new String[] { mTableMarker }, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		mCursorAdapter.swapCursor(cursor);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		mCursorAdapter.swapCursor(null);
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view,
			int position, long id) {
		Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
		Bundle arguments = new Bundle();
		String mbid = cursor.getString(cursor
				.getColumnIndex(Contract.AlbumsColumns.MBID));
		if (TextUtils.isEmpty(mbid)) {
			String artist = cursor.getString(cursor
					.getColumnIndex(Contract.AlbumsColumns.ARTIST));
			String album = cursor.getString(cursor
					.getColumnIndex(Contract.AlbumsColumns.NAME));
			arguments.putString(DetailActivity.ARTIST, artist);
			arguments.putString(DetailActivity.ALBUM, album);
		} else
			arguments.putString(DetailActivity.MBID, mbid);
		arguments.putString(DetailActivity.COVER, cursor.getString(cursor
				.getColumnIndex(Contract.AlbumsColumns.IMAGE_XLARGE)));
		arguments.putString(DetailActivity.MARKER, cursor.getString(cursor
				.getColumnIndex(Contract.AlbumsColumns.NAME)));
		arguments.putSerializable(DetailActivity.STATE, ScreenState.ALBUM);
		mCallbacks.onItemSelected(ScreenState.ALBUM, arguments);
	}
}
